package com.internetCafes.spms.web.sys.service.impl;

import com.internetCafes.spms.common.CommonConstants;
import com.internetCafes.spms.web.sys.dao.MenuInfoMapper;
import com.internetCafes.spms.web.sys.mapper.UserInfoMapper;
import com.internetCafes.spms.web.sys.mapper.UserTokenInfoMapper;
import com.internetCafes.spms.web.sys.model.MenuInfo;
import com.internetCafes.spms.web.sys.model.UserInfo;
import com.internetCafes.spms.web.sys.model.UserTokenInfo;
import com.internetCafes.spms.web.sys.service.ShiroService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private MenuInfoMapper menuInfoMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserTokenInfoMapper userTokenInfoMapper;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == CommonConstants.SUPER_ADMIN){
            List<MenuInfo> functionList = menuInfoMapper.queryList(new HashMap<>());
            permsList = new ArrayList<>(functionList.size());
            for(MenuInfo function : functionList){
                permsList.add(function.getPerms());
            }
        }else{
            permsList = userInfoMapper.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public UserTokenInfo queryByToken(String token) {
        return userTokenInfoMapper.queryByToken(token);
    }

    @Override
    public UserInfo queryUser(Long userId) {
        return userInfoMapper.queryObject(userId);
    }
}
